#!/bin/bash
set -e

if [ -z "$(which php)" ]; then
  echo "A local php installation is required for php development." >&2
  exit 127
fi

# setup test fixtures
BASE_PATH="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
cd $BASE_PATH/test/fixtures/composer

if [ "$1" == "-f" ]; then
  git clean -ffX .
fi

if [ ! -f "composer.phar" ]; then
  EXPECTED_SIGNATURE="$(curl -s https://composer.github.io/installer.sig)"
  php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
  ACTUAL_SIGNATURE="$(php -r "echo hash_file('sha384', 'composer-setup.php');")"

  if [ "$EXPECTED_SIGNATURE" != "$ACTUAL_SIGNATURE" ]; then
    >&2 echo 'ERROR: Invalid installer signature'
    rm composer-setup.php
    exit 1
  fi

  php composer-setup.php
  RESULT=$?
  rm composer-setup.php

  if [ $RESULT -ne 0 ]; then
    >&2 echo 'ERROR: composer.phar installation failed'
    exit $RESULT
  fi
fi

php composer.phar install
